<template>
	<view class="e-upload-main u-flex u-flex-wrap" v-if="show">
		<view :class="['image',count > 1?'image-1':'']" :style="size" v-for="(item,index) in imagesList" :key="index"
			@click="count == 1 && imagesList.length == count?chooseImage():previewImages(index)">
			<u-image :src="item.temporary || ''" :showMenuByLongpress="false" :width="size.width"
				:height="size.height"></u-image>
			<view :class="['status u-flex-center',item.status]">
				<u-loading-icon mode="circle" textSize="10" v-if="item.status == 'uploading'">
				</u-loading-icon>
				<span v-if="item.status != 'success' && item.status != 'uploading'">{{item.status_text}}</span>
			</view>
			<view class="del u-flex-center" @click.stop="del(index)" v-if="singleDel">
				<u-icon name="close" color="#FFFFFF" size="10"></u-icon>
			</view>
		</view>
		<view class="upload-btn" @click="chooseImage()" v-if="count > 1 || (count == 1 && imagesList.length < count)">
			<slot name="btn">
				<view class="btn u-flex-center" :style="size">
					<u-icon name="camera-fill" color="rgb(211, 212, 214)" size="28"></u-icon>
				</view>
			</slot>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 图片数据列表
				imagesList: [],
				// 已上传的图片路径
				uploadImagesList: [],
				// 已上传的图片完整路径
				uploadBaseImagesList: [],
				size: {
					width: '',
					height: '',
				}
			}
		},
		props: {
			name: {
				type: [Number, String],
				default: 'image',
			},
			autoUpload: {
				type: Boolean,
				default: true,
			},
			count: {
				type: [Number, String],
				default: 1
			},
			btnWidth: {
				type: String,
				default: '140rpx'
			},
			btnHeight: {
				type: String,
				default: '140rpx'
			},
			singleDel: {
				type: Boolean,
				default: true,
			},
			show: {
				type: Boolean,
				default: true,
			},
			list: {
				type: Array,
				default: (() => {
					return [];
				}),
			}
		},
		mounted() {
			if (this.list.length > 0) {
				this.list.forEach((item, index) => {
					this.uploadImagesList.push(item);
					var baseFile = item;
					this.uploadBaseImagesList.push(baseFile);
					this.imagesList.push({
						temporary: baseFile,
						status: 'success',
						status_text: '已上传',
						message: '',
						image_url: item,
					})
				})
			}
			this.size.width = this.btnWidth
			this.size.height = this.btnHeight
		},
		methods: {
			// 选择图片
			chooseImage() {
				var that = this;
				// 可选择数量
				if (that.count == 1) { // 可上传一张
					var length = 1;
				} else { // 可上传多张
					var length = that.count - that.imagesList.length;
				}
				if (length <= 0) {
					this.$showToast('您最多可以上传' + that.count + '张')
					return;
				}
				uni.chooseImage({
					count: length, // 默认9
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], // 从相册选择
					success: function(res) {
						if (that.count == 1 && that.imagesList.length == 1) { // 限一张，已上传
							that.imagesList = [];
							that.uploadImagesList = [];
							that.uploadBaseImagesList = [];
						}
						var imagesList = res.tempFilePaths
						imagesList.forEach((item, index) => {
							that.imagesList.push({
								type: res.tempFiles[index].type,
								size: res.tempFiles[index].size,
								name: res.tempFiles[index].name,
								temporary: item,
								status: 'waiting',
								status_text: '待上传',
								message: '',
								image_url: ''
							})
						})
						if (that.autoUpload) { // 自动上传
							that.upload();
						} else {
							that.$emit('chooseComplete', {
								name: that.name, // 唯一标识
								imagesList: imagesList, // 图片列表数据
							})
						}
					},
					fail: function() {},
				});
			},
			async upload() {
				var that = this;
				await that.imagesList.forEach((item, index) => {
					if (item.status != 'success') { // 未上传成功
						item.status = 'uploading';
						item.status_text = '上传中';
						that.uploadFilePromise(item.temporary).then((res) => {
							if (res.code == 200) {
								item.status = 'success'
								item.status_text = '上传成功';
								item.image_url = res.data.file;
								that.uploadImagesList.push(res.data.file)
								that.uploadBaseImagesList.push(res.data.file_url)
								that.complete();
							} else {
								item.status = 'fail';
								item.status_text = '上传失败';
								that.$showToast(res.msg)
							}
						}).catch((e) => {
							item.status = 'fail';
							item.status_text = '网络错误，请重试';
						})
					}
				})
			},
			// 上传图片
			uploadFilePromise(url) {
				var that = this;
				return new Promise((resolve, reject) => {
					let uploadTask = uni.uploadFile({
						url: that.$uploadBaseUrl,
						filePath: url,
						name: 'file',
						header: {
							"Authorization": uni.getStorageSync('token'),
						},
						success: (res) => {
							if (res.statusCode == 200 || res.statusCode == 500 || res.statusCode ==
								400) { // 成功 || 上传失败
								resolve(JSON.parse(res.data))
							} else {
								reject(0)
							}
						},
						fail(err) {
							reject(err)
						}
					});
				})
			},
			// 全屏显示
			previewImages(e) {
				var imageList = [];
				this.imagesList.forEach((item, index) => {
					imageList.push(item.temporary);
				})
				this.$previewImages(imageList, e);
			},
			// 删除图片
			del(e) {
				this.imagesList.splice(e, 1)
				this.uploadImagesList.splice(e, 1)
				this.uploadBaseImagesList.splice(e, 1)
				this.complete();
			},
			complete() {
				this.$emit('complete', {
					name: this.name, // 唯一标识
					imagesList: this.imagesList, // 图片列表数据
					uploadImagesList: this.uploadImagesList, // 已上传的图片列表
					uploadBaseImagesList: this.uploadBaseImagesList, // 已上传的完整图片列表
				})
			},
		}
	}
</script>
<style lang="scss">
	.e-upload-main {

		.image-1 {
			margin: 0 10rpx 10rpx 0;
		}

		.image {
			position: relative;

			.status {
				width: 100%;
				height: 100%;
				position: absolute;
				top: 0;
				left: 0;
				z-index: 10;
				font-size: 20rpx;
			}

			.uploading {
				background-color: rgba(0, 0, 0, 0.2);
				color: #FFFFFF;
			}

			.fail {
				background-color: rgba(0, 0, 0, 0.2);
				color: #000000;
			}

			.del {
				width: 25rpx;
				height: 25rpx;
				position: absolute;
				top: 0;
				right: 0;
				line-height: 10rpx;
				text-align: center;
				z-index: 20;
				border-radius: 0 0 0 20rpx;
				background-color: #2f2f2f;
			}
		}

		.btn {
			margin: 0 10rpx 10rpx 0;
			background-color: #f4f5f7;
		}
	}
</style>